package com.xiao.sulingproduct.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiao.sulingproduct.dao.CommodityDao;
import com.xiao.sulingproduct.entity.ClassifyEntity;
import com.xiao.sulingproduct.entity.CommodityEntity;
import com.xiao.sulingproduct.fegin.EsFeign;
import com.xiao.sulingproduct.service.ClassifyService;
import com.xiao.sulingproduct.service.CommodityService;
import com.xiao.sulingproduct.vo.CommodityVo;
import com.xiao.sulingpublic.utils.PageUtils;
import com.xiao.sulingpublic.utils.Query;
import com.xiao.sulingpublic.utils.R;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;


@Service("commodityService")
public class CommodityServiceImpl extends ServiceImpl<CommodityDao, CommodityEntity> implements CommodityService {
    @Autowired
    private EsFeign esFeign;

    @Autowired
    private ClassifyService classifyService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CommodityEntity> page = this.page(
                new Query<CommodityEntity>().getPage(params),
                new QueryWrapper<CommodityEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public R saveCommodity(CommodityVo commodityVo) {
        CommodityEntity commodity = new CommodityEntity();

        BeanUtils.copyProperties(commodityVo,commodity);
        commodity.setCoClId(Long.valueOf(commodityVo.getClId()));
        //保存数据到数据库
        boolean save = this.save(commodity);
        if(save){
            //保存数据到es中


            //查询分类id对应的分类名
            ClassifyEntity byId = classifyService.getById(commodityVo.getClId());
            commodityVo.setCoId(commodity.getCoId());
            commodityVo.setClName(byId.getClName());
            commodityVo.setClSort(byId.getClSort());
            R save1 = esFeign.save(commodityVo);
            return save1;
        }

       return R.error();
    }

}